﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BIZMA._controls;
using BIZModel;
using BL.BIZControls;

namespace BIZMA._controls.Demo
{
    public partial class List_Companies : BIZListControl, IBIZControlDefaultMethods
    {
        #region Default
        public void DefaultListLoad()
        {
            LoadCompanies();
        }

        public void DefaultListLoad(Guid Id, string loadByType)
        {
            if (loadByType.ToUpper() == LoadByTypeBusinessType)
            {
                LoadByBusinessType(Id);
            }
            else
            {
                throw new NotImplementedException();
            }
        }

        public void DefaultEditNew()
        {
            throw new NotImplementedException();
        }

        public void DefaultEditNew(Guid Id, string editByType)
        {
            throw new NotImplementedException();
        }

        public void DefaultEditLoad(Guid Id)
        {
            throw new NotImplementedException();
        }

        public const string LoadByTypeBusinessType = "BUSINESSTYPE"; 
#endregion

        public const string ListTypeCompany = "COMPANY";
        public const string ListTypeBusinessType = "BUSINESSTYPE";

        private bool CanAddCompanyPopup { get { return ViewState["CanAddCompanyPopup"] != null ? (bool)ViewState["CanAddCompanyPopup"] : false; } set { ViewState["CanAddCompanyPopup"] = value; } }
        private bool CanAddBusinessTypePopup { get { return ViewState["CanAddBusinessTypePopup"] != null ? (bool)ViewState["CanAddBusinessTypePopup"] : false; } set { ViewState["CanAddBusinessTypePopup"] = value; } }

        //OLIKA ID properties som styr frågan för listan tex om man ska hämta utifrån EmployeeId eller PlanningId
        //Styrs av publika metoder
        private Guid BusinessTypeId { get { return ViewState["BusinessTypeId"] != null ? (Guid)ViewState["BusinessTypeId"] : Guid.Empty; } set { ViewState["BusinessTypeId"] = value; } }
        //Olika filter för frågan till listan kan tex vara om man ska visa alla eller aktiva, eller datum mmm
        //Filter sätter man innan man kör de publika metorder som sätter ID properties som finns ovan
        /// <summary>
        /// Sök efter projekt som innehåller detta
        /// </summary>
        public string FilterBy_Name { get { return ViewState["FilterBy_Name"] != null ? (string)ViewState["FilterBy_Name"] : ""; } set { ViewState["FilterBy_Name"] = value; } }
        /// <summary>
        /// Sök efter projekt med kunder med namn som innehåller detta
        /// </summary>
        public Guid FilterBy_BusinessType { get { return ViewState["FilterBy_BusinessType"] != null ? (Guid)ViewState["FilterBy_BusinessType"] : Guid.Empty; } set { ViewState["FilterBy_BusinessType"] = value; } }



        //public delegate void SelectedCompaniesChanged(List_Companies sender, EventArgs e, bool multipleSelect, List<Guid> selectedCompanies);
        //public event SelectedCompaniesChanged SelectedItems;


        //public enum ListObjectType { Company, BusinessType }
        //public delegate void ListClickEventHandler(object sender, Guid ObjectId, ListObjectType ObjectType);
        ///// <summary>
        ///// Ett event som bara körs när HandleListClickEvents är satt till true. Default events för listclick körs inte.
        ///// </summary>
        //public event ListClickEventHandler HandledListClick;
        ///// <summary>
        ///// Om klick i listan ska hanteras av sidan som laddar kontrollen. Tex om man vill ladda en annan url vid klick istället för att visa detaljdialogen
        ///// </summary>
        //public bool HandleListClickEvents { get { return ViewState["HandleListClickEvents"] != null ? (bool)ViewState["HandleListClickEvents"] : false; } set { ViewState["HandleListClickEvents"] = value; } }
        //public List<Guid> SelectedCompanies { get { return ViewState["SelectedCompanies"] != null ? (List<Guid>)ViewState["SelectedCompanies"] : null; } set { ViewState["SelectedCompanies"] = value; } }
        //public bool MultipleSelect
        //{
        //    get { return ViewState["MultipleSelect"] != null ? (bool)ViewState["MultipleSelect"] : true; }
        //    set
        //    {
        //        ddlAction.Items[1].Enabled = value;
        //        ViewState["MultipleSelect"] = value;
        //    }
        //}


        #region This dialog
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack || !InitLoaded)
            {
                InitLoaded = true;
                FillActionList();
                //Gör sådant som man gör på pageload här typ fyll "statisk" dropdown med värden mm 
                //Väldigt ovanligt att man laddar listan härifrån då det oftast görs via en annan metod se public void LOAD_BY_SOMETHING_LIST(int someval)
            }

        }

        protected override void OnInit(EventArgs e)
        {
            base.ActionDropDown = ddlAction;
            base.ListControl = lv;

            base.OnInit(e);

            base.NeedsData += new NeedsDataHandler(List_Companies_NeedsData);

            //här gör man alla init inställningar typ lägga till eventhandlers och annat som styr sidan

            if (ContainerControl != null)
            {               
                ContainerControl.Title = "Företag";
                ContainerControl.ShowButtons(false, false, false, false);

                if (ModalContainerControl != null)
                {
                    ModalContainerControl.Width = 800;
                    ModalContainerControl.Height = 500;
                }
            }

            CanAddCompanyPopup = mcCompany.CanAddPopupControl(BIZControl.DemoCompany);
            CanAddBusinessTypePopup = mcBusinessType.CanAddPopupControl(BIZControl.DemoBusinessType);
            BaseBL.BtnOpenEnabled(btnNew, CanAddCompanyPopup, ViewState);

            mcCompany.ModalClosing += new ModalControlClosing(mcCompany_ModalClosing);
            mcBusinessType.ModalClosing += new ModalControlClosing(mcBusinessType_ModalClosing);
        }

        void mcBusinessType_ModalClosing(object sender, EventArgs e)
        {
            selSearchBusinessType.ReloadBusinessTypes();
            LoadList(false);
        }

        void mcCompany_ModalClosing(object sender, EventArgs e)
        {
            LoadList(false);
        }

        void List_Companies_NeedsData(bool sorting)
        {
            LoadList(sorting);
        }
                

        private void FillActionList()
        {
            ddlAction.Items.Add(new ListItem("--Välj åtgärd--", "-"));
            ddlAction.Items.Add(new ListItem("Välj", "SEL"));
            ddlAction.Items.Add(new ListItem("-------", "-"));
            ddlAction.Items.Add(new ListItem("Radera", "DEL"));

        }

        #endregion
        #region list

        /// <summary>
        /// Här rensas alla id properties som används för frågan till listan
        /// </summary>
        private void ResetIdProperties()
        {
            BusinessTypeId = Guid.Empty;
           
            lv.DataSource = null;
            lv.DataBind();
        }

        //Publika metoder som underliggande sida/kontroll kan ropa på för att ladda kontrollen
        public void LoadCompanies()
        {
            ResetIdProperties();
            LoadList(true);

        }

        public void LoadByBusinessType(Guid businessTypeId)
        {
            ResetIdProperties();
            BusinessTypeId = businessTypeId;
            LoadList(true);
        }


        /// <summary>
        /// Metod som ansvarar för att fylla listan med värden utifrån vilken publik load metod som körts innan
        /// </summary>
        /// <param name="sorting">Talar om ifall sortering ska ändras eller om man ska använda tidigare sortering</param>
        private void LoadList(bool sorting)
        {
            InitLoaded = true;

            BIZMAEntities ent = BaseBL.GetEnt();

            IQueryable<BIZModel.DemoCompany> query = ent.DemoCompanies;

            if (BusinessTypeId != Guid.Empty)
            {
                query = query.Where(q => q.BusinessTypeId == BusinessTypeId);
            }


            if (query != null)
            {
                if (FilterBy_Name != "")
                {
                    query = query.Where(q => q.Name.Contains(FilterBy_Name));
                }

                if (FilterBy_BusinessType != Guid.Empty)
                {
                    query = query.Where(q => q.BusinessTypeId == FilterBy_BusinessType);
                }
            }

            lv.DataSource = (from BIZModel.DemoCompany P in query
                             select new { P.Name, P.DemoBusinessType, P.BusinessTypeId, P.Phone, P.Email, P.CompanyId});

            lv.DataBind();

            if (!sorting)
                lv.ReSort(ViewState);
        }

        //protected void lv_ItemDataBound(object sender, ListViewItemEventArgs e)
        //{
        //    //Här kan man kanske behöva göra speciella funktioner för varje rad i listan om vanliga databind inte fungerar

        //    e.Item.FindControl("chkSel").Visible = MultipleSelect;
        //    e.Item.FindControl("btnSel").Visible = !MultipleSelect;



        //}

        //protected void lv_PagePropertiesChanged(object sender, EventArgs e)
        //{
        //    LoadList(false);
        //}

        //protected void lv_Sorting(object sender, ListViewSortEventArgs e)
        //{
        //    LoadList(true);
        //    ListView lv = (ListView)sender;
        //    lv.ListViewOrder(ViewState, e);
        //}
        #endregion

        #region detail dialog
        protected void OpenDetail_Command(object sender, CommandEventArgs e)
        {
            if (HandleListClickEvents)
            {
                CallHandleClick(this, Guid.Parse(e.CommandArgument.ToString()), ListTypeCompany);
            }
            else
            {


                if (CanAddCompanyPopup)
                {
                    mcCompany.AddDefaultEditLoad(BIZControl.DemoCompany, Guid.Parse(e.CommandArgument.ToString()));

                    //popCompany.AddControl(BIZControl.DemoCompany);

                    //if (popCompany.PopUpControlExists)
                    //{
                    //    Edit_Company uc = ((Edit_Company)popCompany.PopUpControl);
                    //    uc.LoadCompany(Guid.Parse(e.CommandArgument.ToString()));
                    //    popCompany.ModalOpen();

                    //}
                }
            }

        }

        protected void btnNew_Command(object sender, CommandEventArgs e)
        {
            if (HandleNewClickEvent)
            {
                CallNewHandleClick(this, Guid.Empty, ListTypeCompany);
            }
            else
            {
                if (CanAddCompanyPopup)
                {
                    mcCompany.AddDefaultEditNew(BIZControl.DemoCompany);
                    //if (CanAddCompanyPopup)
                    //{
                    //    popCompany.AddControl(BIZControl.DemoCompany);

                    //    if (popCompany.PopUpControlExists)
                    //    {
                    //        Edit_Company uc = ((Edit_Company)popCompany.PopUpControl);
                    //        uc.NewCompany();
                    //        popCompany.ModalOpen();

                    //    }
                    //}
                }
            }
        }



        protected void OpenBTypeDetail_Command(object sender, CommandEventArgs e)
        {
            if (HandleListClickEvents)
            {
                CallHandleClick(this, Guid.Parse(e.CommandArgument.ToString()), ListTypeBusinessType);

                //if (HandledListClick != null)
                //{
                //    HandledListClick(this, Guid.Parse(e.CommandArgument.ToString()), ListObjectType.BusinessType);
                //}
            }
            else
            {

                if (CanAddBusinessTypePopup)
                {
                    mcBusinessType.AddDefaultEditLoad(BIZControl.DemoBusinessType, Guid.Parse(e.CommandArgument.ToString()));

                    //popBusinessType.AddControl(BIZControl.DemoBusinessType);

                    //if (popBusinessType.PopUpControlExists)
                    //{
                    //    Edit_BusinessType uc = ((Edit_BusinessType)popBusinessType.PopUpControl);
                    //    uc.LoadBusinessType(Guid.Parse(e.CommandArgument.ToString()));
                    //    popBusinessType.ModalOpen();

                    //}
                }
            }

        }

        //protected void popCompany_UserControlClosing(object sender, EventArgs e)
        //{
        //    LoadList(false);
        //}

        //protected void popBusinessType_UserControlClosing(object sender, EventArgs e)
        //{
        //    selSearchBusinessType.ReloadBusinessTypes();
        //    LoadList(false);
        //}
        #endregion

        protected void btnSel_Command(object sender, CommandEventArgs e)
        {
            SelectedItems = new List<Guid>();
            SelectedItems.Add(Guid.Parse(e.CommandArgument.ToString()));

            CallListSelect(this, null, MultipleSelect, SelectedItems);

            //if (SelectedItems != null)
            //{
            //    SelectedItems(this, null, MultipleSelect, SelectedCompanies);
            //}

            //if (ContainerControl != null)
            //{
            //    ContainerControl.ModalOkClick();
            //}
        }

        protected void btnAction_Click(object sender, EventArgs e)
        {
            if (ddlAction.SelectedValue != "-")
            {
                if (ddlAction.SelectedValue == "SEL")
                {
                    var selectedKeys = lv.GetSelectedDataKeys("chkSel");
                    SelectedItems = new List<Guid>();
                    foreach (DataKey dk in selectedKeys)
                    {
                        Guid contactId = Guid.Parse(dk.Value.ToString());
                        SelectedItems.Add(contactId);
                    }

                    CallListSelect(this, null, MultipleSelect, SelectedItems);

                    //if (SelectedItems != null)
                    //{
                    //    SelectedItems(this, null, MultipleSelect, SelectedCompanies);
                    //}

                    //if (ContainerControl != null)
                    //{
                    //    ContainerControl.ModalOkClick();
                    //}
                }
                else
                {

                    var selectedKeys = lv.GetSelectedDataKeys("chkSel");
                    BIZMAEntities ent = BaseBL.GetEnt();

                    if (ddlAction.SelectedValue == "DEL")
                    {

                        foreach (DataKey dk in selectedKeys)
                        {
                            Guid companyId = Guid.Parse(dk.Value.ToString());
                            DemoCompany company = ent.DemoCompanies.FirstOrDefault(q => q.CompanyId == companyId);

                            foreach (DemoEmployee emp in company.DemoEmployees.CreateSourceQuery())
                            {
                                ent.DeleteObject(emp);
                            }

                            ent.DeleteObject(company);
                        }
                    }

                    ent.SaveChanges();
                }
            }

            LoadList(false);

        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            FilterBy_Name = txtSeachName.Text;
            FilterBy_BusinessType = selSearchBusinessType.SelectedId;

            LoadList(true);
        }


    }
}